<script setup lang="ts">
import * as echarts from 'echarts'

const props = withDefaults(
  defineProps<{
    width?: string;
    height?: string;
    theme?: string;
    bgColor?: string;
    title?: string;
    subtitle?: string;
    data: any[];
  }>(),
  {
    width: '100%',
    height: '380px',
    data: () => [],
  }
)
// console.log('888888888', props, props.data);

const chartRef = ref()

let state = reactive({
  chart: null as any,
  nvll: ['', null, undefined], // 用于判断实例是否存在
})

onMounted(() => {
  // initChart()
  window.addEventListener('resize', echartsResizeFun)
})

//  使用 keep-alive 缓存了组件，每次进入组件时重新绘制大小
onActivated(() => {
  echartsResizeFun();
})

// 重置echarts图表大小
function echartsResizeFun() {
  state.chart && state.chart.resize();
}

watch(() => [props.data, props.theme, props.bgColor], () => {
  nextTick(() => { // 不加模板未初始化完成，chartRef.value是未定义会报错
    initChart();
  });
}, { deep: true, immediate: true });

function initChart() {
  // 实例存在则销毁
  if (state.nvll.indexOf(state.chart) === -1) state.chart.dispose()
  state.chart = markRaw(echarts.init(chartRef.value, props.theme)) // 使用markRaw返回实例本身，不然有些option选项会失效
  const option = {
    backgroudColor: props.bgColor,
    title: {
      text: props.title,
      subtext: props.subtitle,
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    toolbox: {
    feature: {
      saveAsImage: { // 下载图片
        title: '下载为图片'
      }
    }
  },
    series: [
      {
        name: '单位：元',
        type: 'pie',
        radius: '60%',
        data: props.data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };
  state.chart.setOption(option)
  // console.log(222222, option.series, chartRef.value, state.chart)
}

// 组件销毁前触发
onBeforeUnmount(() => {
  window.removeEventListener('resize', echartsResizeFun)
  if (state.chart) {
    state.chart.dispose();
    state.chart = null;
  }
})

</script>

<template>
  <el-card shadow="hover">
    <div ref="chartRef" :style="{ height: props.height, width: props.width }"></div>
  </el-card>
</template>

<style scoped lang="scss"></style>